package cc.stonemarket.caricature.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.Set;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import cc.stonemarket.caricature.model.Book;

/** 操作Book数据库表的Dao类*/
public class BookDaoImpl implements Idao<Book> {
	
	public static final String TAG = "BookDaoImpl";//用于写日志
	private final SQLiteStatement statement;
	private static final String insert = "insert into book( name, age ) values( ? ,? ) ";

	/**这里的globalDB是由DataManager注入，单例的、全局唯一的*/
	private SQLiteDatabase globalDB;

	/**
	 * 构造函数，注入一个单例的、全局唯一的SQLiteDatabase对象
	 * @param db 注入的SQLiteDatabase对象
	 */
	public BookDaoImpl(SQLiteDatabase db) {
		globalDB = db;
		statement = db.compileStatement(BookDaoImpl.insert);
	}

	/**
	 * 被DBManager的内部类OpenHelper的onCreate方法调用，用于应用程序一开始时创建相应的表
	 * @param OpenHelperDB OpenHelper注入的SQLiteDatabase对象
	 * */
	public static void onCreate(SQLiteDatabase OpenHelperDB) {
		//这里的OpenHelperDB是从OpenHelper类注入的
		OpenHelperDB.execSQL("CREATE TABLE book ( _id INTEGER PRIMARY KEY, name TEXT);");	
	}

	/**
	 * 被DBManager的内部类OpenHelper的onUpgrade方法调用，用于应用程序更新相应的表
	 * @param OpenHelperDB OpenHelper注入的SQLiteDatabase对象
	 * @param oldVersion
	 * @param newVersion
	 * */
	public static void onUpgrade(SQLiteDatabase OpenHelperDB, int oldVersion, int newVersion) {
		//这里的OpenHelperDB是从OpenHelper类注入的
		OpenHelperDB.execSQL("DROP TABLE IF EXISTS book ");
		BookDaoImpl.onCreate(OpenHelperDB);
	}

	
//========================================================================================================
	
	private Book getBook(Cursor cursor){
		
		int columnIndex=-1;
		Book temp = new Book();
		
		columnIndex=cursor.getColumnIndex("id");
		if(columnIndex!=-1){
			temp.setId(cursor.getLong(columnIndex));
		}
		
		columnIndex=cursor.getColumnIndex("cover");
		if(columnIndex!=-1){
			temp.setCover(cursor.getString(columnIndex));
		}
		
		columnIndex=cursor.getColumnIndex("name");
		if(columnIndex!=-1){
			temp.setName(cursor.getString(columnIndex));
		}
		
		columnIndex=cursor.getColumnIndex("letter");
		if(columnIndex!=-1){
			temp.setLetter(cursor.getString(columnIndex));
		}

		columnIndex=cursor.getColumnIndex("author");
		if(columnIndex!=-1){
			temp.setAuthor(cursor.getString(columnIndex));
		}
		
		columnIndex=cursor.getColumnIndex("status");
		if(columnIndex!=-1){
			temp.setStatus(cursor.getString(columnIndex));
		}
		
		columnIndex=cursor.getColumnIndex("clicks");
		if(columnIndex!=-1){
			temp.setClicks(cursor.getInt(columnIndex));
		}
		
		columnIndex=cursor.getColumnIndex("detail");
		if(columnIndex!=-1){
			temp.setDetail(cursor.getString(columnIndex));
		}
		
		columnIndex=cursor.getColumnIndex("updateTime");
		if(columnIndex!=-1){
			temp.setUpdateTime(cursor.getLong(columnIndex));
		}
		
		columnIndex=cursor.getColumnIndex("category");
		if(columnIndex!=-1){
			temp.setCategory(cursor.getString(columnIndex));
		}
		
		columnIndex=cursor.getColumnIndex("region");
		if(columnIndex!=-1){
			temp.setRegion(cursor.getString(columnIndex));
		}
		
		columnIndex=cursor.getColumnIndex("theme");
		if(columnIndex!=-1){
			temp.setTheme(cursor.getString(columnIndex));
		}
		
		columnIndex=cursor.getColumnIndex("webSite");
		if(columnIndex!=-1){
			temp.setWebSite(cursor.getString(columnIndex));
		}
		
		columnIndex=cursor.getColumnIndex("lessons");
		if(columnIndex!=-1){
			temp.setLessons(null);
		}
		
		return temp;
	}
	
	/**直接删除表，再重新建立。而不是逐条删除*/
	public void resetTable() {
		//globalDB.delete("book", null, null);
		BookDaoImpl.onUpgrade(globalDB, 0, 0);
	}

	/**没实现的方法*/
	@Deprecated
	public Cursor getCursor(final String orderBy, final String whereClauseLimit) {
		Log.e(TAG, "还没实现的方法，不能调用！！！");
		throw new UnsupportedOperationException("Not yet implemented");
	}

	/**根据ID,查找记录*/
	public Book select(final long id) {
		Book temp = null;
		Cursor cursor = globalDB.rawQuery("SELECT * FROM Book WHERE _id=?", new String[] { String.valueOf(id) });
		if (cursor.moveToFirst()) {
			temp=this.getBook(cursor);
		}
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return temp;
	}

	public ArrayList<Book> select(String selectSQL, String[] params) {
		ArrayList<Book> set = new ArrayList<Book>();
		Cursor cursor = globalDB.rawQuery(selectSQL,params);
		if (cursor.moveToFirst()) {
			do {
				Book temp=this.getBook(cursor);
				set.add(temp);
			} while (cursor.moveToNext());
		}
		if (!cursor.isClosed()) {
			cursor.close();
		}
		return set;
	}
	
	public ArrayList<Book> selectAll() {
		return this.select("SELECT * FROM Book ORDERBY DESC", null);
	}
	
	public long insert(final Book temp) {
		statement.clearBindings();
		statement.bindString(1, temp.getName());
		statement.bindLong(2, temp.getClicks());
		return statement.executeInsert();
	}

	public void update(Book temp) {
		if ((temp != null) && (temp.getId() != 0)) {
			Book exists = select(temp.getId());
			if (exists == null) {
				throw new IllegalArgumentException("Cannot update entity that does not already exist.");
			}
			globalDB.beginTransaction();
			try {
				final ContentValues values = new ContentValues();
				values.put("name", temp.getName());
				globalDB.update("Book", values, "_id = ?", new String[] {String.valueOf(temp.getId())} );
				globalDB.setTransactionSuccessful();
			} catch (SQLException e) {
				Log.e(TAG, "Error updating Book.", e);
			} finally {
				globalDB.endTransaction();
			}
		} else {
			throw new IllegalArgumentException("Error, Book cannot be null.");
		}
	}
	
	public void delete(final long id) {
		Book a = select(id);
		if (a != null) {
			globalDB.execSQL("DELETE FROM Book WHERE _id=? ", new String[] {String.valueOf(id)} );
		}
	}

}











